//
//  SMCustomNavigationModifier.swift
//  SomePasti
//
//  Created by 李永彬 on 2025/10/4.
//

import SwiftUI

// 修正后的自定义导航栏修饰符
struct SMCustomNavigationModifier: ViewModifier {
    @Environment(\.presentationMode) private var presentationMode
    var config: NavigationConfig
    
    init(config: NavigationConfig) {
        self.config = config
    }
    
    func body(content: Content) -> some View {
        content
            .navigationBarTitle(config.title, displayMode: .inline)
            .navigationBarTitleDisplayMode(.inline)
            .navigationBarBackButtonHidden(!config.showSystemBackButton)
        
//            .navigationBarBackButtonHidden(true)
//            .toolbar {
//                NavigationToolbarContent(
//                    showBackButton: config.showBackButton,
//                    backButtonColor: config.backButtonColor,
//                    image: config.image,
//                    onBack: closeView
//                )
//                // 关键修改2：使用 principal 位置确保标题居中
//                ToolbarItem(placement: .principal) {
//                    Text(config.title)
//                        .font(.headline)
//                        .foregroundColor(config.titleColor)
//                        .lineLimit(1)
//                        .padding(.vertical, 6)
//                }
//            }
    }
    
//    private func closeView() {
//        presentationMode.wrappedValue.dismiss()
//    }
//
}

// 工具栏内容结构
struct NavigationToolbarContent: ToolbarContent {
    let showBackButton: Bool
    let backButtonColor: Color
    let onBack: () -> Void
    let image: Image
    
    init(showBackButton: Bool, backButtonColor: Color, image: Image = Image(systemName: "chevron.left"), onBack: @escaping () -> Void) {
        self.showBackButton = showBackButton
        self.backButtonColor = backButtonColor
        self.image = image
        self.onBack = onBack
    }
    
    var body: some ToolbarContent {
        ToolbarItem(placement: .navigationBarLeading) {
            if showBackButton {
                Button(action: onBack) {
                    HStack(spacing: 6) {
                        image
                            .foregroundColor(backButtonColor)
                            .font(.system(size: 18, weight: .semibold))
                                 .foregroundColor(backButtonColor)
                                 .frame(width: 44, height: 44)
                    }
                    .contentShape(Rectangle())
                    .offset(x: -22) 
                }
                .accessibilityLabel("返回")
            }
        }
    }
}

// 配置结构
struct NavigationConfig {
    var title: String
    var showSystemBackButton: Bool = true
    var titleColor: Color = .black
    var backgroundColor: Color = .white
    var backButtonColor: Color = .black
    var image: Image = Image(systemName: "chevron.left")
}
